from rest_framework import serializers
from .utils import OAuthQQ
from django_redis import get_redis_connection
from .models import QQLogin
from users.models import Users


class QQAuthorSerializers(serializers.Serializer):
    # 校验数据格式
    mobile = serializers.RegexField(regex=r'^1[345789]\d{9}$', label='手机号')
    password = serializers.CharField(min_length=8, max_length=20, label='密码')
    sms_code = serializers.CharField(label='短信验证码')
    access_token = serializers.CharField(label='验证凭据')

    # 重写validate方法
    def validate(self, data):
        # 从前端获取access_token数据
        access_token = data['access_token']
        # 获取身份验证
        openid = OAuthQQ.check_save_user_token(access_token)
        if not openid:
            raise serializers.ValidationError('无效的access_token')

        # 将openid存在校验字典中
        data['openid'] = openid
        # 校验短息验证码
        mobile = data['mobile']
        sms_code = data['sms_code']
        redis_con = get_redis_connection('verify_codes')
        real_sms_code = redis_con.get('sms_%s' % mobile)
        if real_sms_code.decode() != sms_code:
            raise serializers.ValidationError('短信验证码错误')
        # 如果用户存在,检查用户密码
        try:
            user = Users.objects.get(mobile=mobile)
        except Users.DoesNotExist:
            pass
        else:
            password = data['password']
            if not user.check_password(password):
                raise serializers.ValidationError('密码错误')
            data['user'] = user
        return data

    def create(self, validated_data):
        # 获取校验的用户
        user = validated_data.get('user')
        if not user:
            # 用户不存,新建用户
            user = Users.objects.create_user(username=validated_data['mobile'], password=validated_data['password'],
                                             mobile=validated_data['mobile'])
            # 将用户绑定openid
        QQLogin.objects.create(openid=validated_data['openid'], user=user)
        return user
